package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * http://news.qiuyi.cn/html/2013/ylzx_0503/13039.html  求医网
 * 	
 * @author KK
 *
 */
public class QiuyiNewsAnalyse implements AnalyseNews {
	
	private static final String[] regex={
		"http://news.qiuyi.cn/html/[0-9]{4}/[a-z]+_[0-9]{4}/[0-9]+.html",
		"http://news.qiuyi.cn/[0-9]{4}/[a-z]+_[0-9]{4}/[0-9]+.html",
		"http://jibing.qiuyi.cn/[a-z]*/[0-9]{4}/[0-9]{4}/[0-9]+.html"
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title =doc.select("h1#arti_hd").text();	
		content=HtmlCleaner.getContentHtml(url,doc.select("div#arti_bd"));			
		
		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("span#media_name").text();
		author=StringUtils.substringBetween(authorStr, "来源: "," ");
		if(StringUtils.isBlank(author)){
			author=StringUtils.substringAfter(authorStr, "来源: ");
		}
	
		date=DateUtils.matchDate(doc.select("span#pub_date").text());
		if (StringUtils.isNotBlank(title) && date!=null){			
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);	
			news.setType(1);	
		}
		return news;
	}	
	public static void main(String[] args) {
		String url="http://news.qiuyi.cn/2013/xwsd_1212/24517.html";
		QiuyiNewsAnalyse analyse=new QiuyiNewsAnalyse();		
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
